
window.App = {
		
	get : function(url) {
		var data = "<h1> failed to load url : " + url + "</h1>";
		$.ajax({
			async: false,
			url: url,
			success: function(response) {
				data = response;
			}
		});
		return data;
	}

}


App.Company = Backbone.Model.extend({
	urlRoot : "api/company",
	defaults : {
		id: null,
		name: "please insert company name",
		address: "please insert company address",
		password: "please insert user password",
	}
});


App.CompanyCollection = Backbone.Collection.extend({
	url : "api/company",
	model : App.Company
});


App.User = Backbone.Model.extend({
	urlRoot : "api/user",
	defaults : {
		id: null,
		name: "please insert user name",
		email: "please insert user email",
		password: "please insert user password",
	}
});


App.UserCollection = Backbone.Collection.extend({
    url : "api/user",
	model : App.User
});


App.ChromeView = Backbone.View.extend({
	template: _.template( App.get("tpl/chrome.html") ),
	render: function () {
		$(this.el).html(this.template());
		return this;
	},
    events: {
		"click button.login" : "doLogin"
    },
    doLogin : function() {
    	var userCollection = new App.UserCollection();
    	userCollection.fetch({
			data : {
	    		email : $("#email").val(),
	    		password : $("#password").val()
			},
			success : function( users ){
				if( users.models.length == 1)
				{
					App.user = users.models[0];
					App.chromeView.render();
					//App.router.navigate( Backbone.history.fragment , {trigger: true} );
					Backbone.history.loadUrl( Backbone.history.fragment , { trigger: true } )
				}
			}
		});
    },
    updateMenu : function(){
    	$('#chromeViewMenu a').each(function(){
    		var fragment = Backbone.history.fragment == "" ? "home" : Backbone.history.fragment;
    		if( $(this).hasClass(fragment) )
    		{
    			$(this).addClass('active');
    		}
    		else 
			{
    			$(this).removeClass('active');
			}
    	});
    }
});


App.HomeView = Backbone.View.extend({
	template: _.template( App.get("tpl/home.html") ),
	render: function () {
		$(this.el).html(this.template());
		App.chromeView.updateMenu();
		return this;
	},
});


App.AgendaView = Backbone.View.extend({
	template: _.template( App.get("tpl/agenda.html") ),
	render: function () {
		$(this.el).html(this.template());
		App.chromeView.updateMenu();
		return this;
	},
});


App.HealthView = Backbone.View.extend({
	template: _.template( App.get("tpl/health.html") ),
	render: function () {
		$(this.el).html(this.template());
		App.chromeView.updateMenu();
		return this;
	},
});


App.BillingView = Backbone.View.extend({
	template: _.template( App.get("tpl/billing.html") ),
	render: function () {
		$(this.el).html(this.template());
		App.chromeView.updateMenu();
		return this;
	},
});


App.UserListView = Backbone.View.extend({
	template: _.template( App.get("tpl/userList.html") ),
	initialize: function () {
		_.bindAll(this, 'render', 'appendItem', 'create');
	},
	render: function () {
		$(this.el).html(this.template());
        _.each(this.collection.models, this.appendItem, this);
		return this;
	},
    appendItem: function (user) {
    	var userListItemView = new App.UserListItemView({
    		userListView : $(this.el),
    		model : user,
		});
    	userListItemView.userListView = this;
    	$(".users tbody", this.el).append( userListItemView.render().el );
    },
	events: {
		'click a.create': 'create',
	},
	create: function() {
		var view = this;
		var user = new App.User( { companyId : App.user.attributes['companyId'] } );
		this.collection.create(user, {
			success: function() {
				view.undelegateEvents();
				var userEditView = new App.UserEditView({
					model: user,
					el : $(view.el)
				});
				userEditView.render();
			}
		});
	},
});


App.UserListItemView = Backbone.View.extend({
	tagName:"tr",
	template: _.template( App.get("tpl/userListItem.html") ),
	initialize: function () {
		_.bindAll(this, 'render', 'unrender', 'remove', 'edit');
		this.model.bind('remove', this.unrender);
	},
	render:function () {
		$(this.el).html(this.template(this.model.toJSON()));
		return this;
	},
	unrender: function(){
		$(this.el).remove();
	},
	events: {
		'click a.delete': 'remove',
		'click a.edit': 'edit',
	},
	remove: function(e) {
		if(
			!$(e.currentTarget).hasClass("disabled") 
			&& 
			confirm("Deseja eliminar este cliente ?") 
		) {
			this.model.destroy();
		};
	},
	edit: function(){
		this.userListView.undelegateEvents();
		var userEditView = new App.UserEditView({
			model: this.model,
			el : $(this.userListView.el)
		});
		userEditView.render();
	},
});


App.UserEditView = Backbone.View.extend({
	
	template: _.template( App.get("tpl/userEdit.html") ),
	
	events: {
		'click button.save': 'save',
		'click button.cancel': 'cancel',
		'change input' : 'onChange',
	},
	
	render: function () {
		$(this.el).html(this.template(this.model.toJSON()));
		return this;
	},
	
	onChange: function(){
		this.model.set({ name : this.$('input.name').val() });
		this.model.set({ email : this.$('input.email').val() });
		this.model.set({ password : this.$('input.password').val() });
	},
	
	save: function () {
		var self = this;
		this.model.save({}, {
			success : function(model, response){
		    	var userCollection = new App.UserCollection();
		    	userCollection.fetch({
					data : {
			    		companyId : self.model.get('companyId')
					},
					success : function( users ) {
						console.log(users);
						self.undelegateEvents();
						var userListView = new App.UserListView({el : self.el, collection : users });
						userListView.render();
					}
				});
				
			}
		});
	},
	
	cancel: function () {
		var self = this;
    	var userCollection = new App.UserCollection();
    	userCollection.fetch({
			data : {
	    		companyId : this.model.get('companyId')
			},
			success : function( users ) {
				self.undelegateEvents();
				var userListView = new App.UserListView({el : self.el, collection : users });
				userListView.render();
			}
		});
	},
	
});


App.CompanyView = Backbone.View.extend({
	template: _.template( App.get("tpl/company.html") ),
	render: function () {
		$(this.el).html(this.template());
		App.chromeView.updateMenu();
		if(App.user){
			var companyId = App.user.attributes['companyId'];
			this.getCompany(companyId);
			this.getUsers(companyId);
		}
		return this;
	},
	getCompany : function(companyId) {
	},
	getUsers : function(companyId) {
		var userCollection = new App.UserCollection();
		userCollection.fetch({
			data : {
				companyId : companyId
			},
			success : function( users ) {
				var userListView = new App.UserListView({el : $('#users'), collection : userCollection });
				userListView.render();
			}
		});
	}
});


App.Router = Backbone.Router.extend({
	
	routes : {
		""			: "home",
		"agenda"	: "agenda",
		"health"	: "health",
		"billing"	: "billing",
		"company"	: "company",
	},

	initialize: function () {
		App.chromeView = new App.ChromeView({ el : document.body });
		App.chromeView.render();
	},

	home: function () {
		App.homeView = new App.HomeView({el : $('#chromeViewContent') });
		App.homeView.render();
	},

	agenda: function () {
		App.agendaView = new App.AgendaView({el : $('#chromeViewContent') });
		App.agendaView.render();
	},

	health: function () {
		App.healthView = new App.HealthView({el : $('#chromeViewContent') });
		App.healthView.render();
	},

	billing: function () {
		App.billingView = new App.BillingView({el : $('#chromeViewContent') });
		App.billingView.render();
	},

	company: function () {
		App.companyView = new App.CompanyView({el : $('#chromeViewContent') });
		App.companyView.render();
	},
	
});


$(function() {
	App.router = new App.Router;
	Backbone.history.start();
});

